import { invoke } from '@tauri-apps/api/core';

/**
 * HTTP 请求方法
 */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';

/**
 * 请求配置
 */
export interface RequestOptions {
  /** 请求方法 */
  method: HttpMethod;
  /** 请求URL */
  url: string;
  /** URL查询参数 */
  params?: Record<string, string>;
  /** 请求头 */
  headers?: Record<string, string>;
  /** 请求体（JSON格式） */
  body?: any;
  /** 超时时间（秒） */
  timeout?: number;
}

/**
 * 响应数据
 */
export interface ResponseData {
  /** HTTP状态码 */
  status: number;
  /** 响应头 */
  headers: Record<string, string>;
  /** 响应体（JSON格式，如果能解析） */
  body?: any;
  /** 响应体（文本格式） */
  text: string;
}

/**
 * 通过Rust发起HTTP请求
 * 
 * @example
 * ```ts
 * const response = await request({
 *   method: 'GET',
 *   url: 'https://api.example.com/users',
 *   params: { page: '1', limit: '10' }
 * });
 * console.log(response.body);
 * ```
 */
export async function request(options: RequestOptions): Promise<ResponseData> {
  try {
    const response = await invoke<ResponseData>('http_request', { options });
    return response;
  } catch (error) {
    console.error('HTTP请求失败:', error);
    throw error;
  }
}

/**
 * 发起GET请求（简化版）
 * 
 * @param url 请求URL
 * @param params URL查询参数
 * 
 * @example
 * ```ts
 * const data = await get('https://api.example.com/users', { page: '1' });
 * ```
 */
export async function get(url: string, params?: Record<string, string>): Promise<ResponseData> {
  try {
    const response = await invoke<ResponseData>('http_get', { url, params });
    return response;
  } catch (error) {
    console.error('GET请求失败:', error);
    throw error;
  }
}

/**
 * 发起POST请求（简化版）
 * 
 * @param url 请求URL
 * @param body 请求体（JSON格式）
 * @param headers 请求头
 * 
 * @example
 * ```ts
 * const data = await post('https://api.example.com/users', {
 *   name: 'John',
 *   email: 'john@example.com'
 * });
 * ```
 */
export async function post(
  url: string,
  body?: any,
  headers?: Record<string, string>
): Promise<ResponseData> {
  try {
    const response = await invoke<ResponseData>('http_post', { url, body, headers });
    return response;
  } catch (error) {
    console.error('POST请求失败:', error);
    throw error;
  }
}

/**
 * 发起PUT请求
 */
export async function put(
  url: string,
  body?: any,
  headers?: Record<string, string>
): Promise<ResponseData> {
  return request({
    method: 'PUT',
    url,
    body,
    headers,
  });
}

/**
 * 发起DELETE请求
 */
export async function del(url: string, params?: Record<string, string>): Promise<ResponseData> {
  return request({
    method: 'DELETE',
    url,
    params,
  });
}

/**
 * 发起PATCH请求
 */
export async function patch(
  url: string,
  body?: any,
  headers?: Record<string, string>
): Promise<ResponseData> {
  return request({
    method: 'PATCH',
    url,
    body,
    headers,
  });
}

/**
 * 导出默认对象，方便使用
 */
export default {
  request,
  get,
  post,
  put,
  delete: del,
  patch,
};

